//
//  DVUserManager.m
//  DoctorVideo
//
//  Created by 锦食送 on 2019/8/13.
//  Copyright © 2019 lzx. All rights reserved.
//

#import "DVUserManager.h"
#import "DVUserManagerKey.h"
#import "BaseNavigationController.h"
@interface DVUserManager ()

@property (nonatomic, strong) YYDiskCache *cache;

@end

@implementation DVUserManager

+ (instancetype)shareManager
{
    static DVUserManager *userManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        userManager = [[DVUserManager alloc] init];
    });
    return userManager;
}

- (instancetype)init {
    if (self = [super init]) {
        NSString *path = [[UIApplication sharedApplication].documentsPath stringByAppendingString:kMUserInfoStorageKey];
        _cache = [[YYDiskCache alloc] initWithPath:path];
    }
    return self;
}

- (BOOL)loadCacheUserInfo {
    if ([self.cache containsObjectForKey:kMUserInfoStorageKey]) {
        NSDictionary *userDic = (NSDictionary *)[self.cache objectForKey:kMUserInfoStorageKey];
        if (userDic && userDic[kDVUserTokenKey]) {
            _userInfo = userDic;
            return YES;
        } else {
            [self.cache removeObjectForKey:kMUserInfoStorageKey];
            return NO;
        }
    }
    return NO;
}


///public
- (void)updateUserInfo:(NSDictionary * _Nullable)userInfo {
    if (_userInfo && userInfo == nil) {
        if ([self.cache containsObjectForKey:kMUserInfoStorageKey]) {
            [self.cache removeObjectForKey:kMUserInfoStorageKey];
        }
    }
    _userInfo = userInfo;
    if (_userInfo && _userInfo[kDVUserTokenKey]) {
        [self.cache setObject:_userInfo forKey:kMUserInfoStorageKey];
    }
}

- (void)logout {
    [self updateUserInfo:nil];
}

+ (BOOL)isVisitor {
    NSDictionary *userInfo = [DVUserManager shareManager].userInfo;
    return [userInfo.allKeys containsObject:kDVUserTokenKey]?NO:YES;
}

- (BaseTabbarController *)tabBarController
{
    return [BaseTabbarController new];
}

- (BaseNavigationController *)loginController
{
    LoginViewController *loginVC = [[LoginViewController alloc] init];
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginVC];
    return nav;
}

- (void)setRootViewController:(UIViewController *)controller
{
    UIWindow *window = [UIApplication sharedApplication].delegate.window;
    window.rootViewController = controller;
}
@end
